/******************************************************************************************************
Copyright (C) 2013 Mestrelab Research S.L. All rights reserved.

This file is part of the Mnova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*****************************************************************************************************/
/*globals settings, Dir, MessageBox, qsTr, File, print, Application, WebUtils, FileDialog, mainWindow*/
/*jslint plusplus: true, continue: true, bitwise: true*/


function sendEmail() {
	"use strict";
	var i, items, email, showDialog, showSettingsDialog, webUtils, res, text, ssl,
		toKey = "Send Email/To",
		fromKey = "Send Email/From",
		subjectKey = "Send Email/Subject",
		passwordKey = "Send Email/Password",
		loginKey = "Send Email/Account",
		serverKey = "Send Email/Server",
		portKey = "Send Email/Port",
		sSLSKey = "Send Email/SSL",
		authTypeKey = "Send Email/Auth Type",
		lastAttachementFolderKey = "Send Email/Last Folder",
		isHTMLKey = "Send Email/Is HTML",
		dialog = Application.loadUiFile("ricares:sendEmail.ui"),
		settingsDialog = Application.loadUiFile("ricares:sendEmailSettings.ui"),
		server = {},
		debugMode = false,
		files = [],
		currentRow = -1;


	function obfuscatePassword(aString) {

		var newPassword = [];

		for	(i = 0; i < aString.length; i++) {
			newPassword.push(aString.charCodeAt(i) + i);
		}
		return JSON.stringify(newPassword);
	}

	function deobfuscatePassword(aString) {
		var pass = "";

		if (aString && aString.length) {
			try {
				aString  = JSON.parse(aString);
			} catch (ERR) {
				return "";
			}

			for (i = 0; i < aString.length; i++) {
				pass += String.fromCharCode(aString[i] - i);
			}

		}
		return pass;
	}

	function setServerSettings() {
		var pass, data;

		showSettingsDialog = true;
		settingsDialog.widgets.leServer.text = settings.value(serverKey, "");
		settingsDialog.widgets.leLogin.text = settings.value(loginKey, "");
		pass = settings.value(passwordKey, " ");

		data =  settings.value(portKey, "");
		if (data !== "") {
			settingsDialog.widgets.spbxMailPort.value = data;
		}

		data = settings.value(sSLSKey, "");
		if (data !== "") {
			data = (data === "true");
			settingsDialog.widgets.chbxMailSSL.checked = data;
		}

		data = settings.value(authTypeKey, "-");
		if (data !== "-") {
			settingsDialog.widgets.cbMailAuthentication.currentIndex = data;
		}

		if (pass && pass !== "") {
			settingsDialog.widgets.lePassword.text = deobfuscatePassword(pass);
		}

		while (showSettingsDialog) {
			if (!settingsDialog.exec()) {
				return;
			}

			if (settingsDialog.widgets.leServer.text === "" || settingsDialog.widgets.leLogin.text === "") {
				MessageBox.information(qsTr("Server and login are needed"));
			} else {
				showSettingsDialog = false;
			}
		}

		settings.setValue(serverKey, settingsDialog.widgets.leServer.text);
		settings.setValue(loginKey, settingsDialog.widgets.leLogin.text);
		settings.setValue(passwordKey, obfuscatePassword(settingsDialog.widgets.lePassword.text));
		settings.setValue(portKey, settingsDialog.widgets.spbxMailPort.text);
		settings.setValue(sSLSKey, settingsDialog.widgets.chbxMailSSL.checked);
		settings.setValue(authTypeKey, settingsDialog.widgets.cbMailAuthentication.currentIndex);
	}

	function getServerSettings() {
		var server, login, password, data, port, ssl, authType, serverObject;

		server = settings.value(serverKey, "");
		login = settings.value(loginKey, "");
		password = deobfuscatePassword(settings.value(passwordKey, " "));

		data =  settings.value(portKey, "");
		if (data !== "") {
			port = data;
		}

		data = settings.value(sSLSKey, "");
		if (data !== "") {
			data = (data === "true");
			ssl = data;
		}

		data = settings.value(authTypeKey, "-");
		if (data !== "-") {
			authType = data;
		}

		serverObject = {server: server, login: login, password: password, port: port, authentication: authType, ssl: ssl};

		return serverObject;
	}
	function saveDataToRegistry() {
		settings.setValue(fromKey, dialog.widgets.leFrom.text);
		settings.setValue(toKey, dialog.widgets.leTo.text);
		settings.setValue(subjectKey, dialog.widgets.leSubject.text);
	}

	function getDataFromRegistry() {
		dialog.widgets.leFrom.text = settings.value(fromKey, "");
		dialog.widgets.leTo.text = settings.value(toKey, "");
		dialog.widgets.leSubject.text = settings.value(subjectKey, "");
	}

	dialog.widgets.btSettings.clicked.connect(function () {
		setServerSettings();
	});

	dialog.widgets.btAddAttachement.clicked.connect(function () {

		var items, file = FileDialog.getOpenFileName("*", "Select file", settings.value(lastAttachementFolderKey, settings.value(lastAttachementFolderKey, Dir.home())));

		if (file.length) {
			dialog.widgets.twAttachements.insertRow(0);
			items = dialog.widgets.twAttachements.items;
			items[0][0].text = file;
			items[0][0].flags = 35;
			dialog.widgets.twAttachements.items = items;
			file = new File(file);
			settings.setValue(lastAttachementFolderKey, file.absDirPath);
			currentRow = 0;
		}
	});

	dialog.widgets.twAttachements.cellClicked.connect(function (row) {
		currentRow = row;
	});

	dialog.widgets.btRemoveAttachement.clicked.connect(function () {
		dialog.widgets.twAttachements.removeRow(currentRow);
		currentRow = -1;
	});

	dialog.widgets.cbHTML.stateChanged.connect(function (state) {
		dialog.widgets.teText.acceptRichText = state;
		if (state) {
			dialog.widgets.cbSource.enabled = true;
			if (dialog.widgets.cbSource.checked) {
				dialog.widgets.teText.plainText = dialog.widgets.teText.html;
			}
		} else {
			dialog.widgets.cbSource.enabled = false;
			dialog.widgets.teText.html = dialog.widgets.teText.plainText;
		}

	});

	dialog.widgets.cbSource.stateChanged.connect(function (state) {
		if (state) {
			dialog.widgets.teText.acceptRichText = false;
			dialog.widgets.teText.plainText = dialog.widgets.teText.html;
		} else {
			dialog.widgets.teText.acceptRichText = true;
			dialog.widgets.teText.html = dialog.widgets.teText.plainText;

		}

	});


	showDialog = true;

	dialog.widgets.cbHTML.checked = settings.value(isHTMLKey, true);


	if (debugMode) {
		getDataFromRegistry();
	}

	while (showDialog) {
		if (!dialog.exec()) {
			return;
		}

		if (dialog.widgets.leFrom.text === "") {
			MessageBox.critical(qsTr("From field is needed"));
			dialog.widgets.leFrom.setFocus();
			continue;
		}

		if (dialog.widgets.leTo.text === "") {
			MessageBox.critical(qsTr("To field is needed"));
			dialog.widgets.leTo.setFocus();
			continue;
		}

		server = getServerSettings();

		if (!server || !server.server || !server.login) {
			MessageBox.critical(qsTr("Server settings are not available. Please, configure your account and try again"));
			continue;
		}

		if (debugMode) {
			saveDataToRegistry();
		}

		settings.setValue(isHTMLKey, dialog.widgets.cbHTML.checked);

		webUtils = new WebUtils();
		if (!webUtils.isValid) {
			MessageBox.information(qsTr("Error initializing WebUtils"));
			return;
		}

		items = dialog.widgets.twAttachements.items;

		for (i = 0; i < items.length; i++) {
			files.push(items[i][0].text);
		}

		if (dialog.widgets.teText.acceptRichText) {
			text = dialog.widgets.teText.html;
		} else {
			text = dialog.widgets.teText.plainText;
		}

		email = {from: dialog.widgets.leFrom.text, to: dialog.widgets.leTo.text.split(","), subject: dialog.widgets.leSubject.text, text: text, files: files, isHtml: dialog.widgets.cbHTML.checked};
		try {
			mainWindow.setWaitCursor();
			mainWindow.processEvents();
			ssl = server.ssl;
			server.ssl = undefined;
			res = webUtils.sendEmail(email, server, ssl);
			mainWindow.restoreCursor();

			if (res.exitCode === 0) {
				MessageBox.information(qsTr("Your email was sent successfully"));
				showDialog = false;
			} else {
				MessageBox.critical(qsTr("Error sending mail: {0}").format(res.allErrorOutput));
			}

		} catch (ERR) {
			MessageBox.critical(ERR);
			mainWindow.restoreCursor();
		}

	}

}
